<?php

class CategoryController extends MainController implements ControllerInterface {
	
	private static $listType = '__list_type__';
	
	/**
	 * Strona glowna
	 *
	 */
	
	public $tableConfig = array(
		'products_list' => array(
			'o' => array(
				'name' => 'product_description.name',
				'popularity' => 'product.popularity',
				'rate' => 'product.rate',
				'brand' => 'manufacturer.name',
				'rank'	=> 'product.rank',
				'_' => 'rank'

			),
			'v' => 'a',
			't' => 10
		)
	);
	
	protected $tables = array(
		'products_list' => array(
			'o' => array(
				'name' => 'product_description.name',
				'popularity' => 'product.popularity',
				'rate' => 'product.rate',
				'brand' => 'manufacturer.name',
				'_' => 'rate',
			),
			'v' => 'a',
			't' => 10
		)		
	); 

	public function IndexAction($param) {
		$this->AddDescription("");
		$this->AddTitle("");		
	}
	
	public function AjaxSwitchPropertiesCounterAction($param)
	{
		$this->SetNoRender();
		$out = array(
			'status' => 0,
			'data' => array(),
			'cmp' => array(),
		);
		
		if(!Request::IsPost())
		{
			exit;
		}
		
		/*** ustalenie kontekstu ***/
		
		$categoryObj = null;		// tylko w kontekscie kategorii
		$parentCategoryObj = null;	// zawsze jest			
		$activeCompanyObj = null;	// ty;lko w kontekście firmy			
		
		$categories = Request::Get('category');
		
		$categoryObjs = CategoryDAL::GetResult(
			CategoryDAL::GetDalDataObj(
				array(
					'condition' => array(
						'slug' => array(array('condition' => 'IN', 'value' => '(\'' . $categories[0] .'\',\''. $categories[1] .'\')'))
					),
					'join' => array(
						'CategoryDescription' => ' LEFT JOIN category_description ON (category.id_category = category_description.id_category AND category_description.id_language = ' . Registry::Get('APPLICATION_LANGUAGE_ID') . ')'
					)
				)
			)
		);


		if(count($categoryObjs) == 2)
		{

			foreach($categoryObjs as $_cat)
			{
				if($_cat->getSlug() == $categories[0])
				{
					$parentCategoryObj = $_cat;
				} else {
					$categoryObj = $_cat;
				}
			}				
			// categories
		} elseif(count($categoryObjs) == 1) {
			if((int)$categoryObjs[0]->getParent() < 1)
			{
				$parentCategoryObj = $categoryObjs[0];

				$activeCompanyObj = ManufacturerDAL::GetBySlug($categories[1]);

			} else {
				// unexpected result, shouldn't happend
			}
		} else {
			// unexpected result, shouldn't happend
		}		
		
		
		
		/*** end ustalenie kontekstu ***/
		
		/*** lista wyswietlanych cech ***/
		
		$_value = '';

		if($categoryObj)
		{
			$_value = '( id_category = ' . $categoryObj->getId() . ' OR id_category = ' . $parentCategoryObj->getId() .')';
		} else {
			$_value = '( id_category = ' . $parentCategoryObj->getId() .')';
		}		
		
		$dalData = PropertyDAL::GetDalDataObj(
			array(
				'condition' => array(
					'' => array(
						array(
							'condition'=>'', 
							'value'=> $_value
							)
					),
					'active' => array(1),
					'show_in_filters' => array(1),
				),
				'join' => array(
					'PropertyDescription' => ' LEFT JOIN property_description ON (property_description.id_property = property.id_property AND property_description.id_language = ' . Registry::Get('APPLICATION_LANGUAGE_ID') . ' ) ',
					'PropertyGroup' => ' LEFT JOIN property_group ON (property.id_property_group = property_group.id_property_group)'
				)
			)
		);		
		
		$filterProperties = PropertyDAL::GetResult($dalData);
		
		$_ids = array();

		
		foreach($filterProperties as $k => $v)
		{
			$_ids[] = $v->getId();
		}	
		/*** brak cech - zwrocenie pustego wyniku ***/
		if(empty($_ids))
		{
			echo json_encode($out);
			exit;				
		}		
		
		/*** koniec cech ***/
		
		/*** wartosci cech ***/
		$categories = Request::get('category');
		$prop = Request::Get('prop');
		$cmp = Request::Get('cmp');
		$popularity = Request::Get('popularity');
		$rating = Request::Get('rating');	
		$extra = Request::Get('extra');
		
		$popularity = array();
		// rating browse options
		$data = SessionProxy::GetValue('__product_list_selected_popularity__', array());
		SessionProxy::ClearValue('__product_list_selected_popularity__');
		if(isset($data[$categories[0] . $categories[1]]))
		{
			$popularity = $data[$categories[0] . $categories[1]];
			SessionProxy::SetValue('__product_list_selected_popularity__', array($categories[0] . $categories[1] => $popularity));
		}

		$rate = array();
		$data = SessionProxy::GetValue('__product_list_selected_rate__', array());
		SessionProxy::ClearValue('__product_list_selected_rate__');
		if(isset($data[$categories[0] . $categories[1]]))
		{
			$rate = $data[$categories[0] . $categories[1]];
			SessionProxy::SetValue('__product_list_selected_rate__', array($categories[0] . $categories[1] => $rate));
		}

		$rating = array();
		$data = SessionProxy::GetValue('__product_list_selected_rating__', array());
		SessionProxy::ClearValue('__product_list_selected_rating__');
		if(isset($data[$categories[0] . $categories[1]]))
		{
			$rating = $data[$categories[0] . $categories[1]];
			SessionProxy::SetValue('__product_list_selected_rating__', array($categories[0] . $categories[1] => $rating));
		}	
		
		
		$dalData = PropertyValueDAL::GetDalDataObj(
				array(
					'condition' => array(
						'' => array(array(
							'condition' => '',
							'value' => '(id_property = ' . implode(' OR id_property = ', $_ids) .' )'
							)
						),
						'type' => array(									
							'condition' => '=', 
							'value' => Registry::Get('METRIC_SYSTEM_TYPE')
						)
					)
				)
			);		
		
		$dalData->addCondition('parent', 'NULL', 'IS');
		$dalData->addCondition('id_product', 'NULL', 'IS');
		$dalData->setGroupBy('value');
		$dalData->setOrderBy('property_value.id_property_value');

		$pv = PropertyValueDAL::GetResult($dalData);	
		
		/** liczniki cech **/
						
		if(!empty($pv))
		{
			$vArr = array();
			$categoriesIds = array($parentCategoryObj->getId());
			if($categoryObj) $categoriesIds = array_merge ($categoriesIds, array($categoryObj->getId()));

			$results = PropertyValueDAL::GetDefaultsWithCounts($prop, $categoriesIds, (empty($activeCompanyObj)?$cmp:$activeCompanyObj->getId()), $popularity, $rate, $rating);

			foreach($pv as $_p)
			{
				if($_p->getValue() == '')
				{
					continue;
				}

				if(!$_p->getIdProduct())
				{
					$_p->setproductsCount(0);
					if(!isset($_pdv[$_p->getIdProperty()]))$_pdv[$_p->getIdProperty()] = array();
					if(isset($results[$_p->getId()]))$_p->setproductsCount($results[$_p->getId()]);
					$_pdv[$_p->getIdProperty()][] = $_p;	
				}
			}
		}		
		
		/* przypisanie wartosci do cech */
		$data = array();

		foreach($filterProperties as $k => $v)
		{
			if(isset($_pdv[$v->getId()]))
			{
				if(!isset($data[$v->getId()]))$data[$v->getId()] = array();
				foreach($_pdv[$v->getId()] as $p)
				{
					$data[$v->getId()][$p->getId()] = $p->getProductsCount();
				}
			}
		}	
		$out['data'] = $data;
		
		// ustalenie liczników dla firm

		$results = PropertyValueDAL::GetDefaultsWithCountsForCompanies($prop, $categoriesIds, (empty($activeCompanyObj)?$cmp:$activeCompanyObj->getId()), $popularity, $rating);
		
		
		$out['cmp'] = $results;
		
		$out['status'] = 1;
		
		header("Content-type: text/html; charset=utf-8");
		
		echo json_encode($out);
		exit;
		
	}
	
	public function ViewAction($param)
	{
		
		try {

			/** zmienne uzywane w metodzie **/
			$categoryObj = null;
			$parentCategoryObj = null;			
			$activeCompanyObj = null;
			$selectedProperties = array();
			$selectedCompanies = array();
			$popularity = array();
			$rate = array();
			$rating = array();	
			$rating = array();
			$extra = array();
			$filterPropertiesIds = array();
			$premium = array();
			$productsIds = array();
			/** categoryKey, subcategoryKey **/
			$this->smarty->assign('categoryKey', $param['categoryKey']);
			$this->smarty->assign('subCategoryKey', $param['subCategoryKey']);			
			
			/** ustalenie kontekstu - firma czy kategoria **/
			$categoryObjs = CategoryDAL::GetResult(
				CategoryDAL::GetDalDataObj(
					array(
						'condition' => array(
							'slug' => array(array('condition' => 'IN', 'value' => '(\'' . $param['subCategoryKey'] .'\',\''. $param['categoryKey'] .'\')'))
						),
						'join' => array(
							'CategoryDescription' => ' LEFT JOIN category_description ON (category.id_category = category_description.id_category AND category_description.id_language = ' . Registry::Get('APPLICATION_LANGUAGE_ID') . ')'
						)
					)
				)
			);

			if(count($categoryObjs) == 2)
			{
				foreach($categoryObjs as $_cat)
				{
					if($_cat->getSlug() == $param['categoryKey'])
					{
						$parentCategoryObj = $_cat;
					} else {
						$categoryObj = $_cat;
					}
				}				
			} elseif(count($categoryObjs) == 1) {
				if((int)$categoryObjs[0]->getParent() < 1)
				{
					$parentCategoryObj = $categoryObjs[0];
					$activeCompanyObj = ManufacturerDAL::GetBySlug($param['subCategoryKey']);
				} else {
					// unexpected
				}
			} else {
				$this->AddDescription("");
				$this->AddTitle("");
				throw new UserException('Category does\'t exists');
			}	
			
			$this->smarty->assign('parentCategoryObj', $parentCategoryObj);
			$this->smarty->assign('categoryObj', $categoryObj);
			$this->smarty->assign('activeCompanyObj', $activeCompanyObj);	
			
			/** koniec - ustalenie kategoria czy firma **/
			
			/** ustalenei SEO zależne od konspektu **/
			if($categoryObj)
			{
				$categoryDescription = $categoryObj->getCategoryDescription();
				$this->AddDescription($categoryDescription->getSeoDescription());
				$this->AddKeywords($categoryDescription->getSeoKeywords());
				$this->AddTitle($parentCategoryObj->getName());
				$this->AddTitle($categoryObj->getName());
				$this->AddBreadCrumb($parentCategoryObj->getName());
				$this->AddBreadCrumb($categoryObj->getName(), Router::GenerateUrl('mainCategoryView', array('categoryKey' => $parentCategoryObj->getSlug(), 'subCategoryKey'=>$categoryObj->getSlug())));
			} 
			elseif($activeCompanyObj)
			{
				$this->AddDescription($activeCompanyObj->getName());
				$this->AddKeywords($activeCompanyObj->getName());
				$this->AddTitle($parentCategoryObj->getName());
				$this->AddTitle($activeCompanyObj->getName());
				$this->AddBreadCrumb($parentCategoryObj->getName());
				$this->AddBreadCrumb($activeCompanyObj->getName(), Router::GenerateUrl('mainCategoryView', array('categoryKey' => $parentCategoryObj->getSlug(), 'subCategoryKey'=>$activeCompanyObj->getSlug())));				
			}			
			
			/** koniec - SEO **/
			
			/** ustalenie typu widoku **/
			if(isset($_GET['switch']))
			{
				$viewClass = SessionProxy::GetValue(self::$listType, 'list');
				if($viewClass == 'list')
				{
					SessionProxy::SetValue(self::$listType, 'box');
				} else {
					SessionProxy::SetValue(self::$listType, 'list');
				}
			}
			$viewClass = SessionProxy::GetValue(self::$listType, 'list');
			$this->smarty->assign('listType', $viewClass);			
			/** koniec - ustalenie typu wyniku **/
			
			/** odczyt danych z sesji **/
			$data = SessionProxy::GetValue('__product_list_selected_properties__', array());
			SessionProxy::ClearValue('__product_list_selected_properties__');
			if(isset($data[$param['categoryKey'] . $param['subCategoryKey']]))
			{
				$selectedProperties = $data[$param['categoryKey'] . $param['subCategoryKey']];
				SessionProxy::SetValue('__product_list_selected_properties__', array($param['categoryKey'] . $param['subCategoryKey'] => $selectedProperties));							
			}
			$data = SessionProxy::GetValue('__product_list_selected_companies__', array());
			SessionProxy::ClearValue('__product_list_selected_companies__');
			if(isset($data[$param['categoryKey'] . $param['subCategoryKey']]))
			{
				$selectedCompanies = $data[$param['categoryKey'] . $param['subCategoryKey']];
				SessionProxy::SetValue('__product_list_selected_companies__', array($param['categoryKey'] . $param['subCategoryKey'] => $selectedCompanies));
			}			
			$data = SessionProxy::GetValue('__product_list_selected_popularity__', array());
			SessionProxy::ClearValue('__product_list_selected_popularity__');
			if(isset($data[$param['categoryKey'] . $param['subCategoryKey']]))
			{
				$popularity = $data[$param['categoryKey'] . $param['subCategoryKey']];
				SessionProxy::SetValue('__product_list_selected_popularity__', array($param['categoryKey'] . $param['subCategoryKey'] => $popularity));
			}
			$data = SessionProxy::GetValue('__product_list_selected_rate__', array());
			SessionProxy::ClearValue('__product_list_selected_rate__');
			if(isset($data[$param['categoryKey'] . $param['subCategoryKey']]))
			{
				$rate = $data[$param['categoryKey'] . $param['subCategoryKey']];
				SessionProxy::SetValue('__product_list_selected_rate__', array($param['categoryKey'] . $param['subCategoryKey'] => $rate));
			}
			$data = SessionProxy::GetValue('__product_list_selected_rating__', array());
			SessionProxy::ClearValue('__product_list_selected_rating__');
			if(isset($data[$param['categoryKey'] . $param['subCategoryKey']]))
			{
				$rating = $data[$param['categoryKey'] . $param['subCategoryKey']];
				SessionProxy::SetValue('__product_list_selected_rating__', array($param['categoryKey'] . $param['subCategoryKey'] => $rating));
			}
			$data = SessionProxy::GetValue('__product_list_selected_extra__', array());
			SessionProxy::ClearValue('__product_list_selected_extra__');
			if(isset($data[$param['categoryKey'] . $param['subCategoryKey']]))
			{
				$extra = $data[$param['categoryKey'] . $param['subCategoryKey']];
				SessionProxy::SetValue('__product_list_selected_extra__', array($param['categoryKey'] . $param['subCategoryKey'] => $extra));
			}
			$data = SessionProxy::GetValue('__product_list_premium__', array());
			SessionProxy::ClearValue('__product_list_premium__');
			if(isset($data[$param['categoryKey'] . $param['subCategoryKey']]))
			{
				$premium = $data[$param['categoryKey'] . $param['subCategoryKey']];
				SessionProxy::SetValue('__product_list_premium__', array($param['categoryKey'] . $param['subCategoryKey'] => $premium));
			}	
			
			//$productsIds
			$productsIds = SessionProxy::GetValue('__products__ids__', null);
					
			if(Request::IsPost())
			{
				$type = Request::Get('formType');
				switch($type)
				{
					case 'browseOptions':
						{
							// browse options
							SessionProxy::ClearValue('__product_list_selected_properties__');
							$selectedProperties = Request::Get('prop');
							if(!empty($selectedProperties))
							{
								SessionProxy::SetValue('__product_list_selected_properties__', array($param['categoryKey'] . $param['subCategoryKey'] => $selectedProperties));
							}

							SessionProxy::ClearValue('__product_list_selected_companies__');
							$selectedCompanies = Request::Get('cmp');
							if(!empty($selectedCompanies))
							{
								SessionProxy::SetValue('__product_list_selected_companies__', array($param['categoryKey'] . $param['subCategoryKey'] => $selectedCompanies));
							}	
							
							SessionProxy::ClearValue('__product_list_selected_extra__');
							$extra = Request::Get('extra');
							if(!empty($extra))
							{	
								$_extra = array();
								foreach($extra as $k => $v)
								{
									if($v == 0)
									{
										continue;
									}
									$_extra[$k] = $v;
								}
								$extra = $_extra;
								SessionProxy::SetValue('__product_list_selected_extra__', array($param['categoryKey'] . $param['subCategoryKey'] => $extra));
							}	
						}
						break;
					
					case 'ratingBrowseOptions':
						{
							// rating browse options
							$popularity = Request::Get('popularity'); // array(min, max)
							SessionProxy::ClearValue('__product_list_selected_popularity__');
							SessionProxy::SetValue('__product_list_selected_popularity__', array($param['categoryKey'] . $param['subCategoryKey'] => $popularity));
							$rate = Request::Get('rate'); // array(min, max)
							SessionProxy::ClearValue('__product_list_selected_rate__');
							SessionProxy::SetValue('__product_list_selected_rate__', array($param['categoryKey'] . $param['subCategoryKey'] => $rate));
							$rating = Request::Get('rating'); // array(rating_id => array(min, max), rating_id => array(min, max), ... )
							SessionProxy::ClearValue('__product_list_selected_rating__');
							SessionProxy::SetValue('__product_list_selected_rating__', array($param['categoryKey'] . $param['subCategoryKey'] => $rating));
						}
						break;
					
					case 'playersChoice':
						{
							$premium = Request::Get('premium');
							SessionProxy::ClearValue('__product_list_premium__');
							if(!empty($premium))
							{
								SessionProxy::SetValue('__product_list_premium__', array($param['categoryKey'] . $param['subCategoryKey'] => $premium));
							}
						}
						break;
						
					default:
							$productsIds = Request::Get('product_ids');
							SessionProxy::ClearValue('__products__ids__');
							if(!empty($productsIds))
							{
								SessionProxy::SetValue('__products__ids__', $productsIds);
							}
						
						
						break;
				}
			}
			
			/** koniec - obsługa POST**/
			
			/** id kategorii uzywanych w metodzie **/
			$categoriesIds = array($parentCategoryObj->getId());
			if($categoryObj) $categoriesIds = array_merge ($categoriesIds, array($categoryObj->getId()));			
			/** end id kategorii **/
			
			/** uzywane filtry opcji **/
			$dalData = PropertyDAL::GetDalDataObj(
				array(
					'condition' => array(
						'' => array(
							array(
								'condition'=>'', 
								'value'=> ($categoryObj?'( id_category = ' . $parentCategoryObj->getId() . ' OR id_category = ' . $categoryObj->getId() .')':' id_category = ' . $parentCategoryObj->getId())
								)
						),
						'active' => array(1),
						'show_in_filters' => array(1),
					),
					'join' => array(
						'PropertyDescription' => ' LEFT JOIN property_description ON (property_description.id_property = property.id_property AND property_description.id_language = ' . Registry::Get('APPLICATION_LANGUAGE_ID') . ' ) ',
						'PropertyGroup' => ' LEFT JOIN property_group ON (property.id_property_group = property_group.id_property_group)'
					)
				)
			);

			$filterProperties = PropertyDAL::GetResult($dalData);

			foreach($filterProperties as $k => $v)
			{
				$filterPropertiesIds[] = $v->getId();
			}

			if(!empty($filterPropertiesIds))
			{
				/** wartosci dla filtrow **/
				$dalData = PropertyValueDAL::GetDalDataObj(
						array(
							'condition' => array(
								'' => array(array(
									'condition' => '',
									'value' => '(id_property = ' . implode(' OR id_property = ', $filterPropertiesIds) .')'
									)
								),
								'type' => array(
									'condition' => '=', 
									'value' => Registry::Get('METRIC_SYSTEM_TYPE')
								)
							)
						)
					);
				$dalData->addCondition('parent', 'NULL', 'IS');
				$dalData->addCondition('id_product', 'NULL', 'IS');
				$dalData->setGroupBy('value');
				$dalData->setOrderBy('property_value.id_property_value');
				
				$pv = PropertyValueDAL::GetResult($dalData);

				$_pv = array(); // wartosci
				$_pdv = array(); // defaultowe wartosci
				if(!empty($pv))
				{
					$vArr = array();

					$results = PropertyValueDAL::GetDefaultsWithCounts(null, $categoriesIds, (empty($activeCompanyObj)?null:$activeCompanyObj->getId()), $popularity, $rate, $rating);
					
					foreach($pv as $_p)
					{
						if($_p->getValue() == '')
						{
							continue;
						}

						if($_p->getIdProduct())
						{
							if(!isset($_pv[$_p->getIdProperty()]))
							{
								$_pv[$_p->getIdProperty()] = array();
							}
							$_pv[$_p->getIdProperty()][] = $_p;
							if($_p->getParent())
							{
								if(!isset($vArr[$_p->getParent()])) $vArr[$_p->getParent()] = 0;
								$vArr[$_p->getParent()] = $vArr[$_p->getParent()] + $_p->getProductsCount();
							}
						} 
						else
						{
							if(!isset($_pdv[$_p->getIdProperty()]))
							{
								$_pdv[$_p->getIdProperty()] = array();
							}
							if(isset($results[$_p->getId()]))
							{
								$_p->setproductsCount($results[$_p->getId()]);
							} else {
								$_p->setproductsCount(0);
							}
							
							$_pdv[$_p->getIdProperty()][] = $_p;						
						}
					}
				}
				
				foreach($filterProperties as $k => $v)
				{
					if(isset($_pdv[$v->getId()]))
					{
						$v->setPropertyValue($_pdv[$v->getId()]);
						$filterProperties[$k] = $v;
					} elseif (isset($_pv[$v->getId()]))
					{
						$v->setPropertyValue($_pv[$v->getId()]);
						$filterProperties[$k] = $v;
					}
				}

			}

			$this->smarty->assign('filterProperties', $filterProperties);	

			// rating options
			$ratingOptions = ProductVotesTypeDAL::GetResult(ProductVotesTypeDAL::GetDalDataObj(array(
				'condition' => array(
					'' => array(
						array(
							'condition'=>'', 
							'value'=> ($categoryObj?'( id_category = ' . $parentCategoryObj->getId() . ' OR id_category = ' . $categoryObj->getId() .')':' id_category = ' . $parentCategoryObj->getId())
							)
					),					
					'active' => array(1),
				)
			)));
			
			
			$this->smarty->assign('ratingOptions', $ratingOptions);

			/* produkty - wyciagane z kategoriami */
			
			$dalData = null;
			
			if($categoryObj){
				$dalData = ProductDAL::GetDalDataObj(array(
					'tableData' => $this->tableParams['products_list'],
					'condition' => array(
						'product.id_category' => array($categoryObj->getId()),
						'product.active' => array(1),
						'manufacturer.active' => array(1),
					),
					'join' => array(
						'ProductDescription' => ' LEFT JOIN product_description ON (product.id_product = product_description.id_product AND product_description.id_language = '.Registry::Get('APPLICATION_LANGUAGE_ID').')',
						'Manufacturer' => ' LEFT JOIN manufacturer ON (product.id_manufacturer = manufacturer.id_manufacturer AND manufacturer.active = 1)',
						'Category' => ' LEFT JOIN category ON (product.id_category = category.id_category AND category.active = 1)',
						'CategoryDescription' => ' LEFT JOIN category_description ON (product.id_category = category_description.id_category AND category_description.id_language = '.Registry::Get('APPLICATION_LANGUAGE_ID').')'
					)
				));
			} elseif($activeCompanyObj)
			{
				$dalData = ProductDAL::GetDalDataObj(array(
					'tableData' => $this->tableParams['products_list'],
					'condition' => array(
						'product.id_manufacturer' => array($activeCompanyObj->getId()),
						'product.active' => array(1),
						'manufacturer.active' => array(1),
					),
					'join' => array(
						'ProductDescription' => ' LEFT JOIN product_description ON (product.id_product = product_description.id_product AND product_description.id_language = '.Registry::Get('APPLICATION_LANGUAGE_ID').')',
						'Manufacturer' => ' LEFT JOIN manufacturer ON (product.id_manufacturer = manufacturer.id_manufacturer AND manufacturer.active = 1)',
						'Category' => ' LEFT JOIN category ON (product.id_category = category.id_category AND category.active = 1)',
						'CategoryDescription' => ' LEFT JOIN category_description ON (product.id_category = category_description.id_category AND category_description.id_language = '.Registry::Get('APPLICATION_LANGUAGE_ID').')'
					)
				));				
			}
			
			if(!empty($filterPropertiesIds))
			{
				$dalData->addJoin('PropertyValue', ' LEFT JOIN property_value ON(property_value.id_product = product.id_product)');
				$dalData->setGroupBy('product.id_product');	
				$dalData->addCondition('property_value.parent', 'NULL', 'IS NOT');
			}
			
			if(!empty($productsIds))
			{
				$dalData->addCondition('product.id_product', '(' . $productsIds . ')', 'IN');
			}
			
			$_spv = array();
			if(!empty($selectedProperties))
			{
				
				foreach($selectedProperties as $k => $prop)
				{
					$_spv = array_merge($_spv, $prop);
				}
				
				foreach($selectedProperties as $k => $v)
				{
					
					$dalData->addCondition('product.id_product', '(SELECT id_product FROM property_value WHERE parent = ' . implode(' OR parent = ', $v) . ')', 'IN');
				}

			}
			
			if(!empty($extra))
			{
				foreach($extra as $k => $v)
				{
					$idType = null;
					switch($k)
					{
						case 'topRated':
							$idType = 2;
							break;
						
						case 'mostPopular':
							$idType = 3;
							break;
						
						case 'vip':
							$idType = 1;
							break;
					}
					$dalData->addCondition('product.id_product', '(SELECT id_product FROM product_ranking WHERE type = ' . $idType . ')', 'IN');
				}
			}
			
			if(!empty($premium))
			{
				$_conditions = '';
				foreach($premium as $k => $v)
				{
					if($k == 'hand') $_conditions .= 'AND (user_extended_profile.hand = ' . implode(' OR user_extended_profile.hand = ', $v) . ')';
					if($k == 'forehand') $_conditions .= 'AND (user_extended_profile.forehand = ' . implode(' OR user_extended_profile.forehand = ', $v) . ')';
					if($k == 'backhand') $_conditions .= 'AND (user_extended_profile.backhand = ' . implode(' OR user_extended_profile.backhand = ', $v) . ')';
					if($k == 'player_style') $_conditions .= 'AND (user_extended_profile.player_style = ' . implode(' OR user_extended_profile.player_style = ', $v) . ')';
					if($k == 'prefered_court_surface') $_conditions .= 'AND (user_extended_profile.prefered_court_surface = ' . implode(' OR user_extended_profile.prefered_court_surface = ', $v) . ')';
					if($k == 'ntrp') $_conditions .= ' AND (user_extended_profile.ntrp BETWEEN ' . $v['min'] . ' AND ' . $v['max'] . ')';
				}
				if(!empty($_conditions))
				{
					$dalData->addCondition('product.id_product', '(SELECT id_product FROM user_equipment WHERE id_user IN (SELECT user_extended_profile.id_user FROM user_extended_profile  WHERE 1 = 1 ' . $_conditions . ' ))', 'IN');
				}
			}
			
			if(!empty($selectedCompanies))
			{
				$dalData->addCondition('product.id_manufacturer', '(' . implode(', ', $selectedCompanies) . ')', 'IN');
			} else {
				$selectedCompanies = array();
			}
			
			if(isset($popularity['min']) && isset($popularity['max']))
			{
				$dalData->addCondition('product.popularity', $popularity['min'] . ' AND ' . $popularity['max'], 'BETWEEN');
			}
			
			if(isset($rate['min']) && isset($rate['max']))
			{
				$dalData->addCondition('product.rate', $rate['min'] . ' AND ' . $rate['max'], 'BETWEEN');
			}	
			
			if(!empty($rating))
			{
				foreach($rating as $k => $v)
				{
					$dalData->addCondition('product.id_product', '(SELECT id_product FROM product_votes_ranking WHERE id_product_votes_type = ' . $k . ' AND value BETWEEN ' . $v['min'] . ' AND ' . $v['max'] .' )', ' IN');
				}
			}

			$this->smarty->assign('selectedProperties', $selectedProperties);
			$this->smarty->assign('selectedCompanies', $selectedCompanies);
			$this->smarty->assign('selectedPropertyValues', $_spv);

			$dalData2 = clone $dalData;
			$dalData2->setAsCount('count(distinct(product.id_product))');
			$dalData2->setLimit("");
			
			$this->smarty->assign('c', 	ProductDAL::GetResult($dalData2));
			
			$productsList = ProductDAL::GetResult($dalData);
			
			// comapnies
			$dalData =	ManufacturerDAL::GetDalDataObj(
				array(
					'condition' => array(
							'manufacturer.active' => array(1),
							'product.active' => array(1)
						),
					'join' => array(
						'Product' => ' LEFT JOIN product ON (product.id_manufacturer = manufacturer.id_manufacturer)'
						)
					)	
				);
			
			if($categoryObj)
			{
				$dalData->addCondition('product.id_category', $categoryObj->getId());
			} else {
				$dalData->addCondition('manufacturer.id_manufacturer', $activeCompanyObj->getId());
			}		

			$countResults = PropertyValueDAL::GetDefaultsWithCountsForCompanies(null, $categoriesIds, (empty($activeCompanyObj)?null:$activeCompanyObj->getId()));
			$dalData->setGroupBy('manufacturer.id_manufacturer');
			$dalData->setOrderBy('manufacturer.name');
			$result = ManufacturerDAL::GetResult($dalData);
			
			foreach($result as $k => $v)
			{
				if(isset($countResults[$v->getId()]))
				{
					$result[$k]->setProductsCount($countResults[$v->getId()]);
				}
			}			
			
			$this->smarty->assign('filterCompanies', $result);			
			
			$activeProductsIds = array();
			
			foreach($productsList as $product) {
				$activeProductsIds[] = $product->getId();
			}
			
			if(!empty($activeProductsIds))
			{
				$data = array();
				
				$dalObjr = ProductRankingDAL::GetDalDataObj();
				$dalObjr->addCondition('product_ranking.id_product', '(' . implode(', ', $activeProductsIds) .')', 'IN');
				$dalObjr->addJoin('ProductRankingType', ' LEFT JOIN product_ranking_type ON (product_ranking.type=product_ranking_type.id_product_ranking_type AND product_ranking_type.active = 1) ');
				$productRanking = ProductRankingDAL::GetResult($dalObjr);
				
				foreach($productRanking as $item)
				{
					if(!isset($data[$item->getIdProduct()]))$data[$item->getIdProduct()] = array('ranking' => array(), 'vote' => array());
					$data[$item->getIdProduct()]['ranking'][] = $item;
				}
				
				$dalObj = ProductVotesRankingDAL::GetDalDataObj();
				$dalObj->addJoin('ProductVotesType', ' JOIN product_votes_type on ( product_votes_type.id_product_votes_type = product_votes_ranking.id_product_votes_type ) ');
				$dalObj->addCondition('id_product', '(' . implode(', ', $activeProductsIds) .')', 'IN');

				$productVotes = ProductVotesRankingDAL::GetResult($dalObj);
				foreach($productVotes as $item)
				{
					if(!isset($data[$item->getIdProduct()]))$data[$item->getIdProduct()] = array('ranking' => array(), 'vote' => array());
					$data[$item->getIdProduct()]['vote'][] = $item;
				}				
				
				foreach($productsList as $k => $v)
				{
					if(isset($data[$v->getId()]))
					{
						if(isset($data[$v->getId()]['ranking']))
						{
							$productsList[$k]->setProductRanking($data[$v->getId()]['ranking']);
						}
						if(isset($data[$v->getId()]['vote']))
						{
							$productsList[$k]->setProductVotes($data[$v->getId()]['vote']);
						}						
					}
				}
			}

			$this->smarty->assign('productsList', $productsList);
			$this->smarty->assign('popularity', $popularity);
			$this->smarty->assign('rate', $rate);
			$this->smarty->assign('rating', $rating);
			$this->smarty->assign('extra', $extra);
			$this->smarty->assign('premium', $premium);
			$this->AddScript('category.js');
			$this->RunShared('CategoriesAndBrands', $param);
		} catch (Exception $e)
		{
			
//			var_dump($e);
//			exit;
			
			return $this->AddRedirect(Router::GenerateUrl('default'), 0);
		}
		
	}


	/**
	 * Czesc wspolna wszystkich podstron
	 *
	 */
	public function PreDispatch($param) {
		$this->Run($param);
		
	}

	public function PostDispatch($param) {
		
		// nagłówek strony
		$this->RunShared('Header', $param);

		
		// footer
		$this->RunShared('Footer', $param);
	}
	
	
	
	/* parametry w postaci: nazwa1-id-wartosc,nazwa2-id-wartosc */
	private function parseOptions($options)
	{
		$retArray = array();
		
		$_tempArr = explode(',', $options);
		foreach($_tempArr as $item)
		{
			$_tempArr2 = explode('-', $item);
			
			if(count($_tempArr2) == 3)
			{
				if(!isset($retArray[$_tempArr2[0]])) $retArray[$_tempArr2[0]] = array();
				$retArray[$_tempArr2[0]][$_tempArr2[1]] = $_tempArr2[2];
			}
		}
		
		return $retArray;
	}
	
}
?>
